<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<merchant-select
						v-model="queryData.merchantId"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('member.login_ip_member')}:`"
					class="flex-row-container"
					label-width="61px"
				>
					<el-input
						v-model="queryData.ip"
						size="medium"
						:placeholder="$t('risk.please_enter_login_Ip')"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('member.ip_attribution')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-input
						v-model="queryData.ipAttribution"
						size="medium"
						:placeholder="$t('risk.please_enter_Ip_Address')"
						v-input="{ name: 'noNumEmpty' }"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createBy')}:`"
					class="flex-row-container"
					label-width="61px"
				>
					<el-input
						v-model="queryData.createdBy"
						size="medium"
						:placeholder="$t('risk.please_enter_createdBy')"
						v-input="{ name: 'symbols' }"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createAt')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-date-picker
						v-model="registerTime"
						size="medium"
						:picker-options="pickerShortcut2"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_date')"
						:end-placeholder="$t('common.end_date')"
						align="right"
						:clearable="false"
						value-format="timestamp"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('603011')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="handleAdd()"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				class="small-size-table"
				:data="tableData"
				highlight-current-row
				:header-cell-style="getRowClass"
				:max-height="tableHeight"
			>
				<el-table-column
					align="center"
					type="index"
					:label="`${$t('common.serial_number')}`"
					width="85"
				></el-table-column>
				<el-table-column
					prop="merchantId"
					align="center"
					:label="`${$t('common.belong_merchant')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ merchantFilter(scope.row.merchantId) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="ip"
					align="center"
					:label="`${$t('member.login_ip_member')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.ip || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="ipAttribution"
					align="center"
					:label="`${$t('member.ip_attribution')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.ipAttribution || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdBy"
					align="center"
					:label="`${$t('common.createBy')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="`${$t('common.createAt')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>
				<!-- <el-table-column
						prop="updatedBy"
						align="center"
						:label="`${$t('common.last_updateBy')}`"
					></el-table-column>
					<el-table-column
						prop="updatedAt"
						align="center"
						:label="`${$t('common.last_updateAt')}`"
					></el-table-column> -->
				<el-table-column
					prop="remark"
					align="center"
					:label="`${$t('common.remark')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.remark || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="operating"
					align="center"
					:label="`${$t('common.actions')}`"
				>
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('603012')"
							type="danger"
							icon="el-icon-delete"
							size="medium"
							@click="deleteIp(scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:total="total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			v-if="addVisible"
			:title="$t('risk.add_login_ip_white_list')"
			:visible.sync="addVisible"
			:destroy-on-close="true"
			width="30%"
			center
		>
			<el-divider></el-divider>
			<el-form
				ref="formSub"
				:model="dialogData"
				:rules="rules"
				label-width="auto"
			>
				<el-form-item
					:label="`${$t('member.login_ip_member')}:`"
					prop="ip"
					:rules="[
						{
							required: true,
							validator: validateIp,
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model.trim="dialogData.ip"
						maxlength="1000"
						autocomplete="off"
						:placeholder="$t('risk.please_enter_login_Ip')"
						clearable
						style="width:100%"
						oninput="value=value.replace(/\s+/g,'')"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="dialogData.merchantId"
						:placeholder="$t('common.components.select_merchant')"
						style="width:100%"
					></merchant-select>
				</el-form-item>
				<el-form-item :label="`${$t('common.components.remark')}`">
					<el-input
						v-model="dialogData.remark"
						type="textarea"
						maxlength="50"
						style="width:100%"
						v-input="{ name: 'noEmpty' }"
						:placeholder="$t('common.please_enter')"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEdit">
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import MainContent from '@/components/MainContent/index.vue'
const setSearchTime = () => [
	dayjs()
		.subtract(0, 'day')
		.startOf('day'),
	dayjs()
		.subtract(0, 'day')
		.endOf('day')
]
export default {
	// eslint-disable-next-line vue/name-property-casing
	name: 'loginIPWhitelist',
	components: {
		MainContent
	},
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			registerTime: setSearchTime(),
			queryData: { merchantId: '' },
			tableData: [],
			addVisible: false,
			dialogData: { merchantId: '' },
			configStatus: ''
		}
	},
	computed: {
		rules() {
			const merchantId = [
				{
					required: true,
					message: this.$t('member.please_select_a_merchant'),
					trigger: 'change'
				}
			]
			return {
				merchantId
			}
		}
	},
	mounted() {
		if (!this.$store.getters.isZk) {
			this.queryData.merchantId = this.$store.getters.merchantInfo.id
		}
		this.initData()
	},
	methods: {
		initData() {
			this.loading = true
			const create = this.registerTime || []
			const [startTime, endTime] = create
			const params = {
				...this.queryData,
				createdAtBegin: dayjs(startTime).format('YYYY-MM-DD HH:mm:ss'),
				createdAtEnd: dayjs(endTime).format('YYYY-MM-DD HH:mm:ss'),
				...this.getParams()
			}
			this.tableData = []
			this.$api
				.getSelectLoginIpWhitelistPage(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						this.tableData = res.data.record || []
						this.total = res.data.totalRecord || 0
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		search() {
			this.pageNum = 1
			this.initData()
		},
		reset() {
			this.pageNum = 1
			this.queryData = {
				merchantId: this.$store.getters.isZk
					? ''
					: this.$store.getters.merchantInfo.id
			}
			this.registerTime = setSearchTime()
			this.initData()
		},
		// 新增
		handleAdd() {
			this.dialogData = { merchantId: this.queryData.merchantId }
			this.addVisible = true
			// if (this.queryData.merchantId) {
			// 	this.getConfigStatus(this.queryData, 1)
			// } else {
			// 	this.$message.warning(
			// 		this.$t('common.components.select_merchant')
			// 	)
			// }
		},
		// 查询开关状态
		getConfigStatus(val, flag) {
			this.$api.getLoginIpWhitelistConfig(val).then((res) => {
				if (flag === 1 && res.data === '1') {
					this.addVisible = true
				} else if (flag === 2 && res.data === '1') {
					this.$confirm(
						`<strong>${this.$t(
							'risk.is_del_login_ip_white_tip'
						)}</strong><br/><strong style="color:#D9001B">${this.$t(
							'risk.del_risk_level_warning'
						)}</strong>`,
						{
							dangerouslyUseHTMLString: true,
							confirmButtonText: this.$t('common.confirm'),
							cancelButtonText: this.$t('common.cancel'),
							type: 'warning',
							customClass: 'positionIcon'
						}
					)
						.then(() => {
							this.$api
								.setDelIpWhitelist(val)
								.then((res) => {
									if (res?.code === 200) {
										this.$message.success(
											this.$t('common.delete_success')
										)
									} else {
										this.$message({
											type: 'error',
											message: this.$t(
												'common.delete_fail'
											)
										})
									}
									this.total = this.total - 1
									setTimeout(() => {
										this.initData()
									}, 1000)
								})
								.catch((err) => {
									this.tipDialog(err.code)
								})
						})
						.catch(() => {})
				} else {
					this.tipDialog(res.data)
				}
			})
		},
		validateIp(rule, value, callback) {
			const regular = /^((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))$/
			let arr = []
			if (value && value.includes('，')) {
				let str = ''
				str = value.replace(/，/g, ',')
				arr = str.split(',')
			} else if (value) {
				arr = value.split(',')
			} else {
				callback(this.$t('risk.required'))
			}
			if (arr.length > 0) {
				const flag = []
				for (let i = 0; i < arr.length; i++) {
					const ele = arr[i]
					if (ele && !regular.test(ele)) {
						flag.push(i + 1)
					}
				}
				if (flag.length) {
					callback(
						this.$t('risk.format_error') +
							flag.join(this.$t('risk.section')) +
							this.$t('risk.individual')
					)
				} else {
					callback()
				}
			}
		},
		// 提示弹框
		tipDialog(code) {
			if (code === 2981681 || code === '0') {
				this.$confirm(
					"<b class='el-icon-warning' style='font-size:24px;color:#ff8400;margin-right:5px;margin-top:-5px;vertical-align: middle;'></b>" +
						`<label>${this.$t('funds.fund_audit.close')}</label>` +
						this.$t('funds.fund_audit.tip1'),
					this.$t('common.components.tip'),
					{
						dangerouslyUseHTMLString: true,
						showConfirmButton: false,
						showCancelButton: false
					}
				)
					.then(() => {})
					.catch(() => {})
			}
		},
		deleteIp(val) {
			const params = {
				id: val.id,
				merchantId: val.merchantId
			}
			this.getConfigStatus(params, 2)
		},
		subAddOrEdit() {
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					const merchantObj = this.$store.getters.merchantList.find(
						({ id }) => {
							return id === this.dialogData.merchantId
						}
					)
					const ip = this.dialogData.ip.replace(/，/g, ',')
					const params = {
						ip: ip,
						merchantId: this.dialogData.merchantId,
						remark: this.dialogData.remark,
						merchantCode: merchantObj.merchantCode
					}

					this.$api
						.setSaveIpWhitelist(params)
						.then((res) => {
							loading.close()
							this.$message({
								message: `${this.$t('common.add_success')}`,
								type: 'success'
							})
							this.dialogData = { merchantId: '' }
							this.addVisible = false
							setTimeout(() => {
								this.initData()
							}, 1000)
						})
						.catch((err) => {
							loading.close()
							this.tipDialog(err.code)
						})
				}
			})
		},
		handleSizeChange(value) {
			this.pageNum = 1
			this.pageSize = value
			this.initData()
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.initData()
		}
	}
}
</script>

<style lang="scss" scoped>
.formTableBox {
	.borderBox {
		padding: 20px;
		border: 1px solid #dcdfe6;
		.el-input {
			width: 50%;
			margin-bottom: 15px;
		}
		.el-table {
			line-height: 32px;
		}
	}
}
</style>
